<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow;
          header_list[e].value = header_list[e].type == 'input_number' ? ['', ''] : '';
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = '';
        }),
          search_key()
      "
    ></search>

    <div class="p_0_10 m_top10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div>规格列表</div>
        <div class="flex">
          <div class="flex">
            <div>当前服务企业</div>
            <el-select
              class="m_0_10"
              v-model="serviceEnterpriseId"
              @change="search_key()"
            >
              <el-option
                v-for="item in serviceEnterpriseList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </div>
          <el-button type="primary" @click="show_box = true">新增</el-button>
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable;
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true;
                });
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e;
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        highlight-current-row
        v-loading="loading"
        :row-style="{
          height: height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column type="index" label="序号" width="80px"></el-table-column>
        <el-table-column
          label="名称"
          prop="name"
          key="名称"
          sortable
          v-if="header_list[0].showTable"
        >
        </el-table-column>
        <el-table-column
          label="类型"
          key="类型"
          width="80px"
          sortable
          v-if="header_list[1].showTable"
        >
          <template #default="scope: any">
            <div v-if="scope.row.type == 1">铁件</div>
            <div v-else>铝件</div>
          </template>
        </el-table-column>
        <el-table-column
          label="规格"
          prop="productSpecs"
          key="规格"
          sortable
          v-if="header_list[2].showTable"
        >
        </el-table-column>
        <el-table-column
          label="图号"
          prop="productNo"
          key="图号"
          sortable
          v-if="header_list[3].showTable"
        >
        </el-table-column>
        <el-table-column
          label="米重"
          prop="meterWeight"
          key="米重"
          width="80px"
          sortable
          v-if="header_list[4].showTable"
        >
        </el-table-column>
        <el-table-column
          width="140px"
          label="是否主型材"
          key="是否主型材"
          sortable
          v-if="header_list[5].showTable"
        >
          <template #default="scope: any">
            <div v-if="scope.row.isMainProduct">是</div>
            <div v-else>否</div>
          </template>
        </el-table-column>
        <el-table-column
          width="140px"
          label="是否常用"
          key="是否常用"
          sortable
          v-if="header_list[6].showTable"
        >
          <template #default="scope: any">
            <div v-if="scope.row.isCommonUse">是</div>
            <div v-else>否</div>
          </template>
        </el-table-column>
        <el-table-column
          label="排序"
          prop="sort"
          key="排序"
          width="80px"
          sortable
          v-if="header_list[7].showTable"
        >
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="140px">
          <template #default="scope: any">
            <el-button @click="edit_list({ item: scope.row, type: 1 })">编辑</el-button>
            <el-button @click="edit_list({ item: scope.row, type: 2 })">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 500]"
        layout="total,  prev, pager, next, sizes,jumper"
        :total="total"
        @size-change="
          (e) => {
            page_data.pageSize = e;
            get_list();
          }
        "
        @current-change="
          (e) => {
            page_data.current = e;
            get_list();
          }
        "
      />
    </div>

    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="30%"
      destroy-on-close
      @close="resetForm(addMetadataform)"
      :close-on-click-modal="false"
    >
      <template #title
        ><h4 v-if="add_form_data.id == ''">新增规格</h4>
        <h4 v-else>编辑规格</h4></template
      >
      <template #default>
        <el-form
          :model="add_form_data"
          :rules="rules"
          label-width="100px"
          ref="addMetadataform"
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="add_form_data.name" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-radio-group v-model="add_form_data.type">
              <el-radio :label="1">铁件</el-radio>
              <el-radio :label="2">铝件</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="图号">
            <el-input v-model="add_form_data.productNo" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="规格" prop="productSpecs">
            <el-input
              v-model="add_form_data.productSpecs"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="米重" prop="meterWeight">
            <el-input v-model="add_form_data.meterWeight" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="是否主型材">
            <el-radio-group v-model="add_form_data.isMainProduct">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否常用">
            <el-radio-group v-model="add_form_data.isCommonUse">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="add_form_data.sort" placeholder="请输入"></el-input>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addMetadataform)">取消</el-button>
            <el-button
              type="primary"
              @click="submit(addMetadataform)"
              :loading="btn_loading"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { dictData, formatDate, handle_search_key } from "@/utils/check_role"; // 权限校验
import search from "@/view/components/search.vue";
import setTable from "@/view/components/setTable.vue";
import { onBeforeMount, onMounted, ref, onUnmounted, computed } from "vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { FormInstance, ElMessage, ElMessageBox } from "element-plus";
const addMetadataform = ref<FormInstance>();
const list = ref();
const total = ref();
const show_box = ref(false);
const loading = ref(false);
const height_size = ref(1);
const rules = ref({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  productNum: [
    {
      required: true,
      message: "请输入数量",
      trigger: "blur",
    },
  ],
  productSpecs: [{ required: true, message: "请输入规格", trigger: "blur" }],
  meterWeight: [{ required: true, message: "请输入编码", trigger: "blur" }],
  productLength: [{ required: true, message: "请输入长度", trigger: "blur" }],
  teamNo: [{ required: true, message: "请输入组号", trigger: "blur" }],
  productIdentifierId: [{ required: true, message: "选择规格", trigger: "change" }],
});
const header_list = ref();
const header_list_1 = [
  {
    label: "名称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "类型",
    value: "",
    showTable: true,
    type: "select",
    isShow: true,
    options: [
      {
        value: 1,
        label: "铁件",
      },
      {
        value: 2,
        label: "铝件",
      },
    ],
  },
  {
    label: "规格",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "图号",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "米重",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "是否主型材",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: [
      {
        value: true,
        label: "是",
      },
      {
        value: false,
        label: "否",
      },
    ],
  },
  {
    label: "是否常用",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: [
      {
        value: true,
        label: "是",
      },
      {
        value: false,
        label: "否",
      },
    ],
  },
  {
    label: "排序",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
];
const page_data = ref({
  current: 1,
  pageSize: 10,
  name: "",
  productNo: "",
  productSpecs: "",
  meterWeight: "",
  isCommonUse: "",
  type: "",
  isMainProduct: "",
  sort: "",
  serviceEnterpriseId: computed(() => {
    return serviceEnterpriseId.value;
  }),
});
const add_form_data = ref({
  id: "",
  name: "",
  productNo: "",
  productSpecs: "",
  meterWeight: "",
  type: 2,
  isMainProduct: true,
  sort: "",
  isCommonUse: true,
  serviceEnterpriseId: computed(() => {
    return serviceEnterpriseId.value;
  }),
});
const max_height = ref();
const dict_list = ref();
onMounted(() => {
  max_height.value = window.innerHeight - 320; // 带分页的 table 高度
  EventBus.on("refresh", () => {
    get_list();
    ElMessage.success("刷新成功！");
  });
});

onBeforeMount(() => {
  // 根据 路由 区分
  header_list.value = header_list_1;
  get_metadata_list();
  get_serviceEnterpriseList();
  // 字典 判断方式
  dictData("1715631850325544961").then((res) => {
    dict_list.value = res as any;
    dict_list.value.forEach((item) => {
      item.label = item.dictValue;
      item.value = item.dictCode;
    });
  });
});
onUnmounted(() => {
  EventBus.off("refresh");
});
const serviceEnterpriseId = ref();
const serviceEnterpriseList = ref([]);
const get_serviceEnterpriseList = () => {
  axios.request({ url: serviceApi.serviceEnterpriseList, method: "post" }).then((res) => {
    console.log(res);
    serviceEnterpriseList.value = res.data === null ? [] : res.data;
    serviceEnterpriseId.value = res.data === null ? "" : res.data[0].id;
    get_list();
  });
};
const btn_loading = ref(false);
const edit_list = (e) => {
  if (e.type == 1) {
    add_form_data.value = {
      id: e.item.id,
      name: e.item.name,
      productNo: e.item.productNo,
      productSpecs: e.item.productSpecs,
      meterWeight: e.item.meterWeight,
      type: e.item.type,
      isMainProduct: e.item.isMainProduct,
      sort: e.item.sort,
      serviceEnterpriseId: e.item.serviceEnterpriseId,
      isCommonUse: e.item.isCommonUse,
    };
    show_box.value = true;
  } else {
    ElMessageBox.confirm("确定删除该记录？", "", {
      closeOnClickModal: false,
      type: "warning",
    })
      .then(() => {
        axios
          .request({
            url:
              (e.type == 2
                ? serviceApi.profileIdentifier
                : serviceApi.profileIdentifierCode) +
              "/" +
              e.item.id,
            method: "delete",
          })
          .then(() => {
            ElMessage.success("操作成功！");
            setTimeout(() => {
              get_list();
            }, 1000);
          })
          .catch((err) => {
            ElMessage.error(err);
          });
      })
      .catch(() => {});
  }
};
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return;
      btn_loading.value = true;

      axios
        .request({
          url:
            serviceApi.profileIdentifier +
            (add_form_data.value.id == "" ? "" : "/" + add_form_data.value.id),
          method: add_form_data.value.id == "" ? "post" : "put",
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res);
          ElMessage.success("操作成功！");
          setTimeout(() => {
            btn_loading.value = false;
            get_list();
            resetForm(formEl);
          }, 1000);
        })
        .catch((err) => {
          btn_loading.value = false;
          ElMessage.error(err);
        });
    }
  });
};
const currentRowIndex2 = ref(0);
const get_list = () => {
  loading.value = true;
  axios
    .request({
      url: serviceApi.profileIdentifier + "/page",
      method: "post",
      data: page_data.value,
    })
    .then((res) => {
      console.log(res);
      list.value = res.data.content;
      total.value = parseInt(res.data.totalElements);
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      ElMessage.error(err);
    });
};
const metadata_list = ref([]);
const get_metadata_list = () => {
  axios
    .request({
      url: serviceApi.profileMetadata,
      method: "post",
      data: {},
    })
    .then((res) => {
      console.log(res);
      metadata_list.value = res.data;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  add_form_data.value = {
    id: "",
    name: "",
    productNo: "",
    productSpecs: "",
    meterWeight: "",
    type: 2,
    isMainProduct: true,
    sort: "",
    isCommonUse: true,
    serviceEnterpriseId: computed(() => {
      return serviceEnterpriseId.value;
    }),
  };
  show_box.value = false;
};
const search_key = () => {
  page_data.value = {
    current: 1,
    pageSize: 10,
    name: header_list.value[0].value,
    type: header_list.value[1].value,
    productSpecs: header_list.value[2].value,
    productNo: header_list.value[3].value,
    meterWeight: header_list.value[4].value,
    isMainProduct: header_list.value[5].value,
    isCommonUse: header_list.value[6].value,
    sort: header_list.value[7].value,
    serviceEnterpriseId: computed(() => {
      return serviceEnterpriseId.value;
    }),
  };
  get_list();
};
</script>

<style lang="scss" scoped>
.container_main {
  display: flex;
  align-items: center;
  background-color: #fff;
  height: calc(100% - 80px);
  > div:first-child {
    width: 58%;
    height: 100%;
  }
  > div:last-child {
    height: 100%;
    width: 40%;
  }
}
.top_title {
  display: flex;
  align-items: center;
  padding: 2px 5px;
  border: 1px solid #666;
  border-radius: 10px;
  color: #666;
  cursor: pointer;
  &:hover {
    border-color: #3580eb;
    color: #3580eb;
  }
}
.select_me {
  transform: rotate(90deg);
}
</style>
